<template>
  <div>
    <el-card class="mb-20">
      <CategorySelect
        @getCategoryId="getCategoryId"
        :show="!isShowTable"
      ></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <!-- 按钮 -->
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="mb-20"
          :disabled="!category3Id"
          @click="addAttr"
          round
          >添加属性</el-button
        >
        <!-- 表格 -->
        <el-table style="width: 100%" border class="mb-20" :data="attrList">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            label="品牌名称"
            width="200"
          ></el-table-column>
          <el-table-column prop="attrValueList" label="属性值列表">
            <template #default="{ row, $index }">
              <el-tag
                class="mr-10"
                type="success"
                v-for="attr1 in row.attrValueList"
                :key="attr1.id"
                >{{ attr1.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row, $index }">
              <el-button
                class="mr-10"
                type="warning"
                size="medium"
                icon="el-icon-edit"
                @click="updateAttr(row)"
                circle
              ></el-button>
              <el-popconfirm
                title="确定要删除吗？"
                @onConfirm="deleteAttr(row)"
              >
                <el-button
                  type="danger"
                  size="medium"
                  icon="el-icon-delete"
                  circle
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加/修改属性结构 -->
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          round
          size="medium"
          :disabled="!attrInfo.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button round size="medium" @click="cancelSave">取消</el-button>
        <el-table
          style="width: 100%"
          border
          class="mb-20 mt-20"
          :data="attrInfo.attrValueList"
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column prop="attrName" width="width" label="属性值名称">
            <template #default="{ row, $index }">
              <el-input
                v-if="row.inputVisible"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                clearable
                ref="inputRef"
                @blur="inputBlur(row, $index)"
                @keyup.native.enter="inputBlur(row, $index)"
              ></el-input>
              <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column width="width" label="操作">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                size="medium"
                icon="el-icon-delete"
                circle
                @click="deleteAttr($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          round
          size="medium"
          @click="onSave"
          :disabled="attrInfo.attrValueList.length < 1"
          >保存</el-button
        >
        <el-button round size="medium" @click="cancelSave">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 深拷贝
import cloneDeep from "lodash/cloneDeep";
import CategorySelect from "@/components/CategorySelect";
export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      // 平台属性
      attrList: [],
      isShowTable: true,
      // 添加、修改属性值
      attrInfo: {
        attrName: "", //属性名
        attrValueList: [], //属性名的属性值
        categoryId: "", //category3Id
        categoryLevel: 3,
      },
    };
  },
  components: {
    CategorySelect,
  },
  methods: {
    getCategoryId({ categoryId, level }) {
      // console.log(categoryId);
      if (level === 1) {
        this.category1Id = categoryId;
        this.category2Id = "";
        this.category3Id = "";
      } else if (level === 2) {
        this.category2Id = categoryId;
        this.category3Id = "";
      } else {
        this.category3Id = categoryId;
        this.getAttrList();
      }
    },
    // 获取平台属性数据
    async getAttrList() {
      try {
        const { category1Id, category2Id, category3Id } = this;
        let result = await this.$api.reqAttrList(
          category1Id,
          category2Id,
          category3Id
        );
        if (result.code === 200) {
          this.attrList = result.data;
        }
      } catch (error) {
        this.$message.error("获取列表数据失败,请重试");
      }
    },

    // 添加属性值的回调
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        inputVisible: true, // 用这个数据来控制当前这个对象在表格中切换input的显示状态
      });
      // 自动聚焦
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },

    // 添加属性按钮回调
    addAttr() {
      // 切换table的显示与隐藏
      this.isShowTable = false;
      // 清除数据
      this.attrInfo = {
        attrName: "", //属性名
        attrValueList: [], //属性名的属性值
        categoryId: this.category3Id, //category3Id
        categoryLevel: 3,
      };
    },

    // 删除属性值
    deleteAttr(index) {
      this.attrInfo.attrValueList.splice(index, 1); // 删除一个属性值
    },

    // 修改属性值
    updateAttr(row) {
      // 切换table的显示与隐藏
      this.isShowTable = false;
      // 赋值  深拷贝
      this.attrInfo = cloneDeep(row);
      this.attrInfo.attrValueList.forEach((item) => {
        this.$set(item, "inputVisible", false);
      });
    },

    // 取消保存
    cancelSave() {
      // 切换table的显示与隐藏
      this.isShowTable = true;
      // 重置表格数据
      this.attrInfo = {
        attrName: "", //属性名
        attrValueList: [], //属性名的属性值
        categoryId: undefined, //category3Id
        categoryLevel: 3,
      };
    },

    // 点击后聚焦
    inputFocus(row) {
      row.inputVisible = true;
      // 自动聚焦
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },

    // inputBlur失焦事件
    inputBlur(row, index) {
      row.inputVisible = false;
      // 输入的内容不能为空
      if (!row.valueName.trim()) {
        this.attrInfo.attrValueList.splice(index, 1); // 删除这个空数据
        this.$message.error("输入不能为空");
        return;
      }
      // 判断输入的内容不能重复
      const isRepeat = this.attrInfo.attrValueList.some((item, idx) => {
        if (index == idx) {
          return false;
        } else {
          return item.valueName == row.valueName.trim();
        }
      });
      if (isRepeat) {
        this.attrInfo.attrValueList.splice(index, 1); // 删除这个数据
        this.$message.error("输入的内容不能重复，请重新输入");
        return;
      }
    },

    // 保存
    async onSave() {
      // 收集categoryId的值 - 组装数据
      // this.attrInfo.categoryId = this.category3Id;
      try {
        await this.$api.reqAddAttr(this.attrInfo);
        // 切换table的显示与隐藏
        this.isShowTable = true;
        this.$message.success("保存成功");
        // 重新获取数据进行展示
        this.getAttrList();
      } catch (error) {
        this.$message.error("保存失败,请重试");
      }
    },

    // 删除平台属性
    async deleteAttr(row) {
      try {
        await this.$api.deleteAttr(row.id);
        this.$message.success("删除成功");
        // 重新获取数据进行展示
        this.getAttrList();
      } catch (error) {
        this.$message.error("删除失败,请重试");
      }
    },
  },
};
</script>

<style scoped>
</style>